conditional compiling depending on template type

Hello,

I wish to conditionally compile a function depending on the template type provided. I need to do so to overcome compile error
error: type 'double' cannot be used prior to '::' because it has no members T::myTypeFunction()

I have tried something like this:
1
2
3
4
5
6
7
8
9
10
11
template <class T>
void Foo(){
//[...] do something simple
if(typeid(T).name()==typeid(double).name()){
                    res = sizeof(double);
                }
                else {
                    res = T::myTypeFunction()
                }
//[...] finish the simple task
}


which it actually works as soon as I do not call Foo<double>() or Foo<whatever non implementing ::myTypeFunction() for what it matters.

I do understand the problem is the compiler try to generate code for Foo<double> and produces the error because it cannot know runtime value for typeid(T).name()==typeid(double).name()).

Is there an elegant conditional compiling option can help solve this problem?
You can create a specialised template; a version just for double.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

template <class T>
void Foo()
{
      std::cout << "Other version \n";
}

template <>
void Foo<double>()
{
       std::cout << "Double version \n";
}

int main()
{
  Foo<int>();
  Foo<double>();
}



Also;
I do understand the problem is the compiler try to generate code for Foo<double> and produces the error because it cannot know runtime value for typeid(T).name()==typeid(double).name()).


I think the problem is actually this: res = double::myTypeFunction() That's the problem; trying to call a class member function on double.
Last edited on
Use a constexpr if: https://en.cppreference.com/w/cpp/language/if#Constexpr_If

1
2
3
4
5
6
7
8
9
10
11
template <class T>
void Foo(){
	//[...] do something simple
	if constexpr (std::is_same_v<T, double>){
		res = sizeof(double);
	}
	else {
		res = T::myTypeFunction();
	}
	//[...] finish the simple task
}
constexpr works exactly as I needed. Thanks!
Topic archived. No new replies allowed.