car*_*rlo 6 c++ interface static-polymorphism
我想知道如何在不使用虚函数的情况下在 C++ 中声明一个接口。经过一些互联网搜索,我整理了这个解决方案:
#include <type_traits>
using namespace std;
// Definition of a type trait to check if a class defines a member function "bool foo(bool)"
template<typename T, typename = void>
struct has_foo : false_type { };
template<typename T>
struct has_foo<T, typename enable_if<is_same<bool, decltype(std::declval<T>().foo(bool()))>::value, void>::type> : true_type { };
// Definition of a type trait to check if a class defines a member function "void bar()"
template<typename T, typename = void>
struct has_bar : false_type { };
template<typename T>
struct has_bar<T, typename enable_if<is_same<void, decltype(std::declval<T>().bar())>::value, void>::type> : true_type { };
// Class defining the interface
template <typename T>
class Interface{
public:
Interface(){
static_assert(has_foo<T>::value == true, "member function foo not implemented");
static_assert(has_bar<T>::value == true, "member function bar not implemented");
}
};
// Interface implementation
class Implementation:Interface<Implementation>{
public:
// If the following member functions are not declared a compilation error is returned by the compiler
bool foo(bool in){return !in;}
void bar(){}
};
int main(){}
Run Code Online (Sandbox Code Playgroud)
我计划在我将只使用静态多态的项目中使用这种设计策略。我将在项目中使用的 C++ 标准是 C++11。
您认为这种方法的优缺点是什么?
可以对我提出的代码进行哪些改进?
编辑 1: 我刚刚意识到不需要从接口继承。也可以使用此代码:
class Implementation{
Interface<Implementation> unused;
public:
bool foo(bool in){return !in;}
void bar(){}
};
Run Code Online (Sandbox Code Playgroud)
编辑 2-3: static_assert 解决方案(有或没有 CRTP)和标准 CRTP 之间的一个主要区别是 CRTP 不保证派生类实现所有接口成员。例如,以下代码正确编译:
#include <type_traits>
using namespace std;
template< typename T>
class Interface{
public:
bool foo(bool in){
return static_cast<T*>(this)->foo(in);
}
void bar(){
static_cast<T*>(this)->bar();
}
};
class Implementation: public Interface<Implementation>{
public:
// bool foo(bool in){return !in;}
// void bar(){}
};
int main(){}
Run Code Online (Sandbox Code Playgroud)
仅当需要函数foo或bar时,编译器才会返回有关缺少成员函数的错误。
在我看来,static_assert 解决方案更像是一个接口声明,而不是单独的 CRTP。
实现静态多态性的常用方法是使用CRTP。
使用此模式,您可以定义一个模板化接口类,其方法转发到模板:
// Interface
template <typename T>
struct base {
void foo(int arg) {
static_cast<T*>(this)->do_foo(arg);
}
};
Run Code Online (Sandbox Code Playgroud)
您实现从基类继承并实现方法:
// Implementation
struct derived : base<derived> {
void do_foo(int arg) {
std::cout << arg << '\n'
}
};
Run Code Online (Sandbox Code Playgroud)
这种模式的优点是它看起来“感觉”很像常规运行时多态性,并且错误消息通常非常正常。因为所有代码对编译器都是可见的,所以所有内容都可以内联,因此没有开销。
看来您想要实现概念(精简版)。在尝试实施之前,您可能需要阅读这篇文章。
如果没有编译器支持,您可以部分实现这个想法。您的static_assert想法是表达接口需求的已知方式。
考虑Sortable链接中的示例。您可以创建一个类模板Sortable,用于static_assert断言有关模板参数的各种想法。您向用户解释他们需要实现一组特定的方法,并且为了强制实现该组方法,他们需要使用Sortable<TheirClass>一种或另一种方法。
为了表达,就在函数声明中。你的函数需要 a 的想法Sortable,你将不得不求助于这样的东西:
template <typename Container>
auto doSomethingWithSortable (Container&) -> std::enable_if<Implements<Container, Sortable>>::type;
Run Code Online (Sandbox Code Playgroud)