考虑下一个例子:
#include <iostream>
#include <typeinfo>
template< int N, typename T >
struct B
{
struct C;
};
template< typename T >
struct B< 0, T >::C
{
typedef T type;
};
template< int N, typename T >
struct B< N, T >::C
{
typedef T type[N];
};
i
注意:,这似乎是一个问题的转贴:
我已经将C++模板专门化的问题归结为一个简单的案例。
它由一个简单的2参数模板类Thing组成,我想在其中专门介绍Thing<A,B>::doSomething() for B=int。
#include <cstdio>
// A 3-parameter template class.
template <class A, class B>
class Thing
{
public:
Thing(A a, B b) : a_(a), b_(b) {}
B doSomething();
private:
比方说,我们需要一个函数模板,它应该根据类型返回一个整数:
template<typename T>
int get_type();
此外,我们对它进行了专门化,有两种类型:
template<>
int get_type<int>()
{
return TYPE_INT;
}
// And so on for other types...
这是很好的工作,但不适用于数组类型。我可以做到以下几点:
template<>
int get_type<char[]>()
{
return TYPE_STRING;
}
编译器“同意
我想写以下几点:
template <typename S, typename T> void foo() {
/* code for the general case */
}
template <typename T> void foo<MySType,T>() {
/* partially specialized code - for any kind of T, but when S is MySType */
}
或者,在其他情况下,下列情况:
template <typename S, typename T> voi
我需要使用C++模板在编译时匹配类型列表中的类型。这是我的代码,但它编译成一个错误。知道我怎么能修好它吗?
template <typename T, typename X, typename... Rs>
struct match
{
using test = typename std::conditional<std::is_same<T, X>::value, X, bool>::type;
using more = typename match<T, Rs...>::type;
using type = typen
当我在带有一个模板参数的类上使用模板部分专门化时,我可以专门化这样的方法:
#include <cstdlib>
template< std::size_t Dim >
class Test
{
public:
int foo();
};
template< std::size_t Dim >
inline int Test< Dim >::foo()
{
return 0;
}
template<>
inline int Test< 1 >::foo()
{
return 1;
}
int main(
我尝试实现一个模板类,并希望将其限制为特定于某个给定的模板类。例如,在下面的代码中,我希望定义模板类CTest,该模板类只能专用于某些模板参数T的std::vector<T>。对于其他模板参数,类应该是未定义的。如何实现模板类?
// the interface should be something like following
//template <typename std::vector<T> >
//class CTest<std::vector<T> >;
int main(int argc, char* argv[
在C++中,我有一个关于特定模板友谊的问题。在C++ Primer一书中,具体的模板友谊如下所示:
template <class T> class Foo3;
template <class T> void templ_fcn3(const T&);
template <class Type> class Bar {
// each instantiation of Bar grants access to the
// version of Foo3 or templ_fcn3 instantiated with the
我在这样的头文件中定义了一个类(尽管这是一个精简的版本):
my_class.hpp
// header guard
template<typename T, std::size_t First, std::size_t Second, class Enable = void>
class other_class;
template<typename T, std::size_t Size, class Enable = void>
class my_class; // I have my reasons
templa