开发者

How can I make a variable of the same type as another using templates?

开发者 https://www.devze.com 2023-01-03 22:51 出处:网络
I\'d like to create a variable which matches the type of another variable by way of a template such that if the other variable ever changes type to match, the one derived from it via a template also c

I'd like to create a variable which matches the type of another variable by way of a template such that if the other variable ever changes type to match, the one derived from it via a template also changes its type.

How can I do this with templates in C++?

The purpose is to ensure that when I read from disk into a temporary variable that the number of byte开发者_Python百科s read from disk exactly matches the actual variable. In this case, I am going to ignore the value so don't want to read to the actual variable, but need to make sure I read the right number of bytes before moving on to keep things in sync.


With the current standard, I don't think you can do this without some really hardcore metaprogramming tricks. The solution wouldn't be ideal. edit> In fact I think it's not possible.

The next standard will provide decltype operator that let you get the type of a variable or expression :

A a;
decltype(a) b; // b is of type A

If you use a recent compiler, like MSVC10 or Gcc4.5, this feature is already available (check the auto keyword too).


If you don't have decltype available in your compiler, you can write a template function to accomplish this. It's kind of ugly but it will get the job done.

template<typename T>
T read_alike(int fd, T const &unusedVar)
{
    T realVar;
    if (::read(fd, &realVar, sizeof(realVar)) != sizeof(realVar)
        throw std::runtime_error("read failed or incomplete");
    return realVar;
}

You'd call it like:

MyClass myObj;

MyClass newObj = read_alike(fd, myobj);
0

精彩评论

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