2014-06-11 117 views
-1

我不得不承认标题听起来有点奇怪。但我会证明你什么,我想在C++:修改类内部的泛型引用

class MyClass { 
public: 
    template<typename T> 
    void set(T& val) { 
    _value = val; 
    } 

    void someOtherFunction() { 
    _value = std::string("12") //this is always a std::string 
    } 

private: 
    boost::any _value; 
}; 

int main() { 
    MyClass a; 
    int val; 
    a.set(val); 
    a.someOtherFunction(); 

    std::cout << val << std::endl; 

} 

所以我希望里面主要VAL成为12.这也应该对任何(浇注)工种我设定MyClass.set()。 有没有机会实现这个目标?

感谢您的帮助!

回答

0

由于std::string不能转换为int(或其他许多方面),我假设你想分析字符串。 boost::any还存储通过值而不是引用,所以你可能不得不实现自己的容器,这样的事情:

#include <sstream> 
#include <memory> 
#include <iostream> 

struct value_holder 
{ 
    virtual ~value_holder() {} 
    virtual void operator=(const std::string& source) = 0; 
}; 

template<typename T> struct value_holder_impl: value_holder 
{ 
    T& value; 

    value_holder_impl(T& v): value(v) {} 

    void operator=(const std::string& source) { 
    std::istringstream(source) >> value; 
    } 
}; 

class MyClass { 
public: 
    template<typename T> 
    void set(T& val) { 
    _value = std::make_shared<value_holder_impl<T>>(val); 
    } 

    void someOtherFunction() { 
    *_value = std::string("12"); 
    } 

private: 
    std::shared_ptr<value_holder> _value; 
}; 

int main() { 
    MyClass a; 
    int val; 
    a.set(val); 
    a.someOtherFunction(); 

    std::cout << val << std::endl; 
} 
+0

完美!非常感谢。由于某种原因,只有流媒体运算符(istringstream)不起作用。但我必须使用boost :: lexical_cast因为某些特定的类型转换。 – Rollmops