模板类模板方法专业化

时间:2013-11-19 16:00:40

标签: c++ templates template-specialization

为什么以下代码无法编译?

template <typename T>
struct X
{
    template <typename R>
    R default_value();
};

template <typename T>
int X<T>::default_value<int>()
{
    return -1;
}

它说

x.cpp:17:30: error: template-id ‘default_value<int>’ in declaration of primary template
x.cpp:17:5: error: prototype for ‘int X<T>::default_value()’ does not match any in class ‘X<T>’
x.cpp:13:7: error: candidate is: template<class T> template<class R> R X::default_value()

我也试过

template <typename T>
template <>
int X<T>::default_value<int>()
{
    return -1;
}

但是这给了我另一个编译错误

prog.cpp:11: error: invalid explicit specialization before '>' token
prog.cpp:11: error: enclosing class templates are not explicitly specialized
prog.cpp:12: error: template-id 'default_value<int>' for 'int X<T>::default_value()' does not match any template declaration

我也尝试过为结构做同样的事情

template <typename T>
struct X
{
    template <typename R> struct default_value;
};

template <typename T>
template <>
struct X<T>::default_value<int>
{
    static int get() { return -1; }
};

同样的问题。

如何解决?

2 个答案:

答案 0 :(得分:1)

无法明确专门化成员模板。考虑:

template <class T>
struct X
{
  template <class U> struct Y;
};

......现在(想象一下我们可以这样做):

template <class T>
  template <>
  struct X<T>::Y<int>
{};

...对于哪个T我们明确专门的X?

如果在我们明确专业化的定义之后,有人在一个编译单元中执行此操作...

void foo()
{
  X<int>::Y<int> xy;
}

...然后在另一个......(有效代码,顺便说一句)。

template <>
  template<>
  struct X<int>::Y<int>
{};

void foo()
{
  X<int>::Y<int> xy;
}

...这意味着同一类的多个定义???

如前所述,这个问题得到了很好的处理here

现在,考虑到默认值实际上取决于类型T,也许可以从类型T中获取它。

template <class T>
struct X
{
  static T defaultValue(){ return T::defaultValue(); }
};

或者更好的是,可以根据T是否具有成员defaultValue来改变defaultValue的行为。

答案 1 :(得分:0)

template <typename T>
template <>
int X<T>::default_value<int>()
{
    return -1;
}

应该没问题。 Similar topic...