不带模板参数使用的 C++ 模板名称

标签 c++

<分区>

我一直在使用“const ObjArray&”作为 ObjArray 模板的参数,但没有考虑它。它似乎工作正常,但当我再次阅读时它看起来很糟糕。不应该是“const ObjArray<T> &”吗?不带参数引用模板名可以吗?它是否在下面工作只是因为编译器假定 T 被声明为内联?

template <class T>
class ObjArray : public BArray
{
public:
    inline ObjArray() :
        BArray(sizeof(T), NULL)
    {
    }

    inline ObjArray(const ObjArray& src) :
        BArray(sizeof(T), NULL)
    {
        copyFrom((ObjArray&)src);
    }

    inline ObjArray(ObjArray& src) :
        BArray(sizeof(T), NULL)
    {
        copyFrom(src);
    }
    ...
};

最佳答案

不,这种用法是正确的:在类模板中,类名指的是模板的那个实例,所以模板参数不是必需的:

template<typename T>
struct foo
{
    foo( const foo& ); //Copy ctor. foo is the same as foo<T>
};

此行为在标准的 14.6.1 本地声明名称 点中有明确定义(强调我的):

14.6.1 Locally declared names [temp.local]
Like normal (non-template) classes, class templates have an injected-class-name (Clause 9). The injected-class-name can be used with or without a template-argument-list. When it is used without a template-argument-list, it is equivalent to the injected-class-name followed by the template-parameters of the class template enclosed in <>. When it is used with a template-argument-list, it refers to the specified class template specialization, which could be the current specialization or another specialization.

请注意,syntax 只是当前模板实例的别名。如果您需要具有其他参数的相同模板,则需要使用经典语法明确指定它。例如:

template<typename U>
operator foo<U>() const //Implicit conversion to other instance of the template
{
    return ...;
}

关于不带模板参数使用的 C++ 模板名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23045559/

相关文章:

c++ - std::array 在存储大对象时是否仍然缓存友好?

c++ - Windows:基于事件的重叠 IO 与 IO 完成端口,真实世界性能

c++ - C++ 中的测试条件

C++/BOOST:condition_variable::wait( )/notify( ) 是否确保线程等待的顺序?

C++ signed 和 unsigned int 与 long long 速度

c++ - 如何使用类似 Type() 的语法对 Type* 指针进行值初始化?

c++ - 如何从字符串中获取 int(使用类似 char 数组的字符串)

c++ - 我怎么知道在 OpenMP "for directive"中完成了多少作业?

c++ - 如何使用 WinRT 在 Windows 8 Metro 应用程序中播放声音文件?

c++ - 静态变量指针?