从未模板化类的模板化成员函数实例化模板化类
Instantiating a templated class from a templated member function of a not templated class
我一直在尝试理解boost::any代码的工作原理,并尝试编写以下代码
class placeholder
{
public:
virtual ~placeholder() {}
virtual placeholder* clone() const=0;
};
//And this is the wrapper class template:
template<typename ValueType>
class holder : public placeholder
{
public:
holder(ValueType const & value) : held(value) {}
virtual placeholder* clone() const
{return new holder(held);}
private:
ValueType held;
};
//The actual type erasing class any is a handle class that holds a pointer to the abstract base class:
class any
{
public:
any() : content(NULL) {}
template<typename ValueType>
any( const ValueType & value): content(new holder(value)) {}
~any()
{delete content;}
// Implement swap as swapping placeholder pointers, assignment
// as copy and swap.
private:
placeholder* content;
};
int main( int argc, char ** argv ) {
return 0;
}
当我尝试编译代码时,我得到以下错误:
test.cxx: In constructor 'any::any(const ValueType&)':
test.cxx:33: error: expected type-specifier before 'holder'
test.cxx:33: error: expected ')' before 'holder'
上面的错误出现在
行any( const ValueType & value): content(new holder(value)) {}
我真的不明白为什么不能在这里推断出类型。我读了为什么我不能从模板化函数调用模板化类的模板化方法,但是无法解决我的问题
谁来帮帮我。
由于holder
是模板,而c++不根据构造函数推导模板参数,因此在any
的构造函数中实例化模板参数时必须指定模板参数。
template <typename ValueType>
any( const ValueType & value): content(new holder<ValueType>(value)) {}
相关文章:
- 如何使用非默认构造函数实例化模板化类
- C++ - 使用另一个类的构造函数实例化一个对象
- 与参数匹配的友元模板函数实例化
- 在保证复制的世界中构造函数实例化
- SFINAE 和模板函数实例化:为什么在启用了 SFINAE 类型的函数参数中使用模板参数时无法推断模板参数?
- 防止复制构造函数实例化 C++11 类"deleting"
- 如何键入定义一个专门的 std::set 模板,使用特定的比较函数实例化
- 使用不同类型的模板函数实例化
- C 调用模板构造函数实例化
- 为什么很清楚模板函数实例化不会内联
- 模板函数实例化文件
- 模板函数实例化的可移植性问题
- 模板函数实例化 自定义数据类型的问题
- 模板类成员函数实例化
- C++.对象使用错误的构造函数实例化
- C++如何用参数化构造函数实例化对象
- 为什么无法使用复制构造函数实例化"non const"而可以在没有复制构造函数的情况下实例化配对?
- 双模板化函数实例化失败
- 延迟 crtp 基类中的成员函数实例化
- 如何根据容器的元素类型启用模板函数实例化