Hey guys,
I'd like to use C++20 concepts to define interfaces. Usually I'd define interfaces using virtual functions but in this particular case I do not want any runtime overhead.
Concepts should generate some meaningful compiler errors
Let's consider this class
1 2 3 4 5 6 7 8 9
|
template<typename String_T, typename Layer_T>
class FooClass
{
public:
String_T m_strFoo;
void foo() {
const String_T str = Layer_T::getId();
}
};
|
a valid typename which can be passed as Layer_T could look like this
1 2 3 4 5 6 7 8 9 10 11 12
|
class SimpleIF_Impl
{
public:
static std::string getName()
{
return "";
}
static void* getId()
{
return nullptr;
}
};
|
creating an instance of foo class like this
FooClass<std::string, SimpleIF_Impl> f1;
would work.
Now I want to ensure via concepts that a correct IF is passed as a template parameter
When I'm creating a simple concept that does not rely on template parameters like this
1 2 3 4 5
|
template<typename T>
concept SimpleIF = requires (T a) {
{ T::getName() } -> std::same_as<std::string>;
{ T::getId() } -> std::same_as<void*>;
};
|
and adjusting my class to this
1 2 3 4 5 6 7 8 9
|
template<typename String_T, SimpleIF Layer_T>
class FooClass
{
public:
String_T m_strFoo;
void foo() {
const std::string str = Layer_T::getId();
}
};
|
I can create an instance of FooClass without any errors like this
FooClass<std::string, SimpleIF_Impl> f1;
Now what I haven't figured out is. How to deal with a concept which depends on a template parameter itself
1 2 3 4 5 6
|
template<typename T>
concept TemplatedIF = requires (T a) {
{ T::getName() } -> std::same_as<std::string>;
typename T::task_type;
{ T::getId() } -> std::same_as<typename T::task_type>;
};
|
after adjusting
1 2
|
template<typename String_T, TemplatedIF Layer_T>
class FooClass
|
I cannot create an instance of FooClass any more
writing
FooClass<std::string, SimpleIF_Impl> f1;
gives me a compiler error
"template argument deduction failed for FooClass() String_T"
Tested with latest MSVC17
Could you help me out here? How can i handle templated concepts?