2017-03-15 6 views
0

では動作しません:例えば、スカラー値をキャストユーザー定義変換演算子は、私は、単純なプリミティブ型のラッパを持っている参照

template <typename T> 
class Scalar { 
public: 
    explicit Scalar(T value) : value{value} {} 

    Scalar(Scalar&& other) = default; 
    Scalar& operator=(Scalar&& other) = default; 
    Scalar(const Scalar& other) = default; 
    Scalar& operator=(const Scalar& other) = default; 

    template <typename U> 
    explicit operator Scalar<U>() { 
    return Scalar<U>{static_cast<U>(this->value)}; 
    } 

    inline T getValue() const noexcept { return this->value; } 
private: 
    T value; 
}; 

はうまく動作しますが、何とかそれを参照するために失敗しました

auto a = Scalar<double>{2.54}; 
Scalar<int> b = static_cast<Scalar<int>>(a); // works 

const auto& c = a; 
Scalar<int> d = static_cast<Scalar<int>>(c); // fails 

ここでコンパイルエラー(ここではhttp://rextester.com/GOPYU13091確認することができます)、ここで問題になる可能性がありますどのような任意のアイデアですか?

source_file.cpp: In function ‘int main()’: 
source_file.cpp:31:47: error: no matching function for call to ‘Scalar(const Scalar<double>&)’ 
    Scalar<int> d = static_cast<Scalar<int>>(c); 
              ^
source_file.cpp:12:3: note: candidate: Scalar<T>::Scalar(const Scalar<T>&) [with T = int] <near match> 
    Scalar(const Scalar& other) = default; 
^
source_file.cpp:12:3: note: conversion of argument 1 would be ill-formed: 
source_file.cpp:31:47: error: could not convert ‘c’ from ‘const Scalar<double>’ to ‘const Scalar<int>&’ 
    Scalar<int> d = static_cast<Scalar<int>>(c); 
              ^
source_file.cpp:10:3: note: candidate: Scalar<T>::Scalar(Scalar<T>&&) [with T = int] <near match> 
    Scalar(Scalar&& other) = default; 
^
source_file.cpp:10:3: note: conversion of argument 1 would be ill-formed: 
source_file.cpp:31:47: error: could not convert ‘c’ from ‘const Scalar<double>’ to ‘Scalar<int>&&’ 
    Scalar<int> d = static_cast<Scalar<int>>(c); 
              ^

答えて

5

これは、非const問題ではなく、オブジェクトの問題対基準対constあります。私の作品

auto& c = a; 
Scalar<int> d = static_cast<Scalar<int>>(c); 
を使用して

constメンバ関数

template <typename U> 
explicit operator Scalar<U>() const { 
    return Scalar<U>{static_cast<U>(this->value)}; 
} 

にユーザ定義の変換演算子を変更することにより

も必ずその次作品になります。

const auto& c = a; 
Scalar<int> d = static_cast<Scalar<int>>(c); 
関連する問題