1

このコードはどのようにコンパイルされませんか? なぜbs[1]に推論できないのboolですか?

この問題を解決する一般的な方法はありますか?

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

template<typename T> struct StringConverter{};
template<> struct StringConverter<bool>{
    std::string operator()(const bool &i){ return i?"true":"false"; }   
};

template<typename T> std::string to_string(const T &val){
    return StringConverter<T>()(val);
}

int main(){
    // this does not compile
    std::bitset<10> bs;
    std::cout << to_string(bs[0]) << std::endl;

    // this does
    const std::bitset<10> bs_const;
    std::cout << to_string(bs_const[0]) << std::endl;
}

コンパイラ エラー:

main.cpp:12:12: error: type 'StringConverter<std::bitset<10>::reference>' does not provide a call operator
    return StringConverter<T>()(val);
           ^~~~~~~~~~~~~~~~~~~~
main.cpp:18:18: note: in instantiation of function template specialization 'to_string<std::bitset<10>::reference>' requested here
    std::cout << to_string(bs[0]) << std::endl;
                 ^
1 error generated.
4

2 に答える 2

1

の宣言operator[]を確認すると、2 つのオーバーロードがあることがわかりますconst。1 つは返さboolれて 2 番目の例で使用され、もう 1 つconstは type のオブジェクトを返しますstd::bitset::reference

bool&後者はビットフィールドの変更に使用され、特定のビットをアドレス指定する必要があるため、決して a にすることはできません。あなたが遭遇した問題は、これらのプロキシの戻り値の型では非常に一般的です (これは私が言及する必要がある場所ですvector<bool>)。

std::bitset::reference可能な解決策として、変換可能であるという事実を使用できます(そして、特殊bool化に使用する可能性のある他の考えられる型には変換できません)。StringConverter

于 2017-12-09T22:44:38.867 に答える