开发者

C++ Template: What happens if we put wrong thing in our template class

C++ templates allow we put whatever in our objects with template arguments. However, if our template arguments use functions/variables which belong to certain types, 开发者_JS百科how do we check?

template<typename BarType>rguments

class Foo {

public:

     Foo() { bar = new BarType() }

private:

     BarType * bar;

}

Foo<Bar> …

BarType could be anything derived from a Bar superclass.

What happens if we invoke some functions which only belong to Bar in our Foo class? What happens if we pass non-BarType? Do we have anyway to check?


You will get a compile-time error if your templated code makes reference to members that the actual parameter doesn't provide when you try to instantiate the template. So don't worry, you won't be able to break anything.

Think of templates as a code-generation mechanism. Whether the generated code actually makes sense can sometimes only be determined when you actually try it.


Given the class template TempFoo below, you see that it calls the example function of the templated T type in its constructor. The first two types work because they both define example; the third doesn't.

template<typename T>
class TempFoo
{
    void TempFoo() {
        T obj;
        obj.example();
    }
};

class First {
    void example() {}
};

class Second {
    void example() {}
};

class Third {
};

int main()
{
     TempFoo<First> f; // works
     TempFoo<Second> s; // works
     TempFoo<Third> t; // doesn't

}


Whatever you're giving in the tempalte parameter list is simple a place place holder. Compiler will repalce with appropriate types according to the type of object which is used to instantiate the template class. A compile-time error will be appear if the object doesn't satify the operations done in the functions. Also it's a good practice to use 'T' as place holder.


An easy way to ensure that the template parameter derives from the base class:

template<typename BarType>
class Foo 
{
    // ...
    ~Foo() { Bar* p = (BarType*)0; }
};

The compiler will type-check the assignment, generating an error if Bar isn't an unambiguous supertype of BarType, and then optimize away the unused local variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜