这是一段简单的代码:

#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 shortinit()。我的问题是:(a)可行吗? (b)如果(a),如何?

在搜索(a)时,我以为可以在class A<T>中添加仿函数,在V中初始化其状态(值为init()),在print(double)中调用它,但是我从未使用过对象,所以我不知道这是不是要走的路。我基本上乐于接受任何建议,我唯一需要的是对print的调用保持不变(因为我将从不知道unsigned short V值的其他类中调用它。

谢谢 !

最佳答案

单程:

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; }
};

关于c++ - 依赖模板的实现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12703106/

10-11 22:47
查看更多