我可以想象下面的代码:
template <typename T> class X
{
public:
T container;
void foo()
{
if(is_vector(T))
container.push_back(Z);
else
container.insert(Z);
}
}
// somewhere else...
X<std::vector<sth>> abc;
abc.foo();
怎么写,才能编译成功?我知道类型特征,但是当我定义时:
template<typename T> struct is_vector : public std::false_type {};
template<typename T, typename A>
struct is_vector<std::vector<T, A>> : public std::true_type {};
无法编译:
error: no matching function for call to 'std::vector<sth>::insert(Z)'
static_assert 也不是我想要的。有什么建议吗?
这是我想要实现的目标的简短示例 (SSCCE):http://ideone.com/D3vBph
最佳答案
叫做标签调度:
#include <vector>
#include <set>
#include <type_traits>
template<typename T> struct is_vector : public std::false_type {};
template<typename T, typename A>
struct is_vector<std::vector<T, A>> : public std::true_type {};
template <typename T>
class X {
T container;
void foo( std::true_type ) {
container.push_back(0);
}
void foo( std::false_type ) {
container.insert(0);
}
public:
void foo() {
foo( is_vector<T>{} );
}
};
// somewhere else...
int main() {
X<std::vector<int>> abc;
abc.foo();
X<std::set<int>> def;
def.foo();
}
关于c++ - 编译时检查是模板类型还是 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21512678/