1

这是一段简单的代码:

#include <iostream>
#include <fstream>

template<typename T>
class A {
    public:
        T _v;
        template<unsigned short V> void init() { _v *= V; }
        void print(double txt) { std::cout << "Initialized with ?? : " << txt << std::endl; }
};

int main() {
    A<double> foo;
    foo._v = 3.5;
    foo.init<2>();
    foo.print(foo._v);

    A<int> bar;
    bar._v = 2;
    bar.init<5>();
    foo.print(bar._v);
}

我希望有一个A::print(double)依赖于的函数的实现unsigned short V,例如,替换??unsigned short已经init()实例化的。我的问题是:(a)它可行吗?(b) 如果 (a),如何?

class A<T>在搜索 if ( a V)init()时,我想我可以print(double)向去。我基本上对任何建议持开放态度,我唯一需要的是调用print保持不变(因为我会从其他不知道unsigned short V.

谢谢 !

4

1 回答 1

0

单程:

template<typename T>
class A {
    public:
        T _v;
        unsigned short _v2;
        template<unsigned short V> void init() { _v2 = V;  _v *= V; }
        void print(double txt) { std::cout << "Initialized with "
            << _v2 << " : " << txt << std::endl; }
};

或者为什么不:

template<typename T, unsigned short V>
struct A {
        T _v = V;
        void print(double txt) { std::cout << "Initialized with "
            << V << " : " << txt << std::endl; }
};
于 2012-10-03T06:43:46.583 回答