It is possible to check for the existence of class member functions. An implementation of the check could be taken from this answer: https://stackoverflow.com/a/257382/2492801.
Now a static_assert can be used to ensure that a certain class has an implementation of a needed method. But if the class is templated, I do not know whether such a static assertion is possible or how to do it - except if I do the static_assert for a concrete template parameter selection. The latter is possible, but it feels wrong...
Please consider the following code:
#include <iostream>
// SFINAE test
template <typename T>
class has_helloworld
{
typedef char one;
struct two
{
char x[2];
};
template <typename C>
static one test(decltype(&C::helloworld));
template <typename C>
static two test(...);
public:
enum
{
value = sizeof(test<T>(0)) == sizeof(char)
};
};
template <int number>
struct Hello
{
int helloworld()
{
return 0;
}
// The next line is not possible since class Hello is not complete yet.
// static_assert(has_helloworld<Hello<number>>::value);
};
template <int number>
struct Generic
{
};
int main()
{
// This is possible, but I don't like it
static_assert(has_helloworld<Hello<3>>::value);
// The next two lines are not possible because a template declaration cannot appear at block scope.
// template <int number>
// static_assert(has_helloworld<Hello<number>>::value);
std::cout << has_helloworld<Hello<2>>::value << std::endl;
std::cout << has_helloworld<Generic<2>>::value << std::endl;
return 0;
}
Here is a Godbolt link: https://godbolt.org/z/c3bKKMxcc
Is there a possibility in C++ to do a "templated static assert", so a static_assert where I check a property of a class that depends on a template parameter without choosing a dummy value for that parameter?
Clarification: In my case in practice the template parameter does not play a role, it just impedes the static_assert. So like in the code example, all template structs Hello have the required method regardless of the parameter number.
Helloanywhere that does not implementhelloworld()? Are you expecting all specializations to be considered in your assert?Hellohashelloworldand other is not? There is no way to list all possibilities of template.