Reputation: 2907
Suppose I have this:
template <typename CharType>
class StringView
{
private:
const CharType* m_String;
size_t m_Length;
public:
template <typename CharTraits, typename StringAlloc>
inline StringView(const std::basic_string<CharType, CharTraits, StringAlloc>& str) :
m_String(str.c_str()), m_Length(str.length())
{
}
inline const CharType* Str() const
{
return m_String;
}
};
Is there a way to prevent construction from a temporary std::string
? That is:
std::string GetStr()
{
return "hello";
}
int main()
{
std::string helloString = "hello";
StringView<char> str1 = helloString; // This is ok
StringView<char> str2 = GetStr(); // I want this to be a compiler error
std::cout << str1.Str() << std::endl;
std::cout << str2.Str() << std::endl;
}
I need this to work on at least VS 2015 C++ compiler. Platform specific hacks are welcome if there's no portable solution.
Upvotes: 0
Views: 215
Reputation: 217810
You may delete the constructor:
template <typename CharTraits, typename StringAlloc>
StringView(std::basic_string<CharType, CharTraits, StringAlloc>&&) = delete;
Upvotes: 6