CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    1,342

    Get decltype to deduce member variable constness

    Consider the following code:

    Code:
    template <typename T>
    class really_long_complicated_typename
    {
    public:
        really_long_complicated_typename(T& x) : x(x) {}
    private:
        T& x;
    };
    
    template <typename T>
    really_long_complicated_typename<T> f(T& t)
    {
        return really_long_complicated_typename<T>(t);
    }
    
    
    class A
    {
        class C {};
        C c;
    public:
        A() {}
    
        decltype(f(c)) get_c() const { return f(c); }
    };
    
    int main()
    {
        const A a;
        a.get_c();
    }
    g++ gives the error:

    Code:
    test.cpp: In member function really_long_complicated_typename<A::C> A::get_c() const:
    test.cpp:24: error: conversion from really_long_complicated_typename<const A::C> to non-scalar type really_long_complicated_typename<A::C> requested
    The problem is that the expression f(c) in the return statement is really_long_complicated_typename<const A::C>, but decltype doesn't "know" that this is a const member function, so decltype(f(c)) is deduced to be really_long_complicated_typename<A::C>.

    Is there a way around this?
    Old Unix programmers never die, they just mv to /dev/null

  2. #2
    Join Date
    Oct 2008
    Posts
    1,456

    Re: Get decltype to deduce member variable constness

    have you tried "auto get_c() const -> decltype(f(c)) { return f(c); }" or the more explicit "auto get_c() const -> decltype(f( this->c )) { return f(c); }" instead ?
    Last edited by superbonzo; September 28th, 2010 at 03:57 AM.

  3. #3
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    1,342

    Re: Get decltype to deduce member variable constness

    Quote Originally Posted by superbonzo View Post
    have you tried "auto get_c() const -> decltype(f(c)) { return f(c); }" or the more explicit "auto get_c() const -> decltype(f( this->c )) { return f(c); }" instead ?
    The first makes no difference.

    The second gives the error "invalid use of 'this' at top level".

    Perhaps it's just my compiler that doesn't support this feature fully? I am using g++ 4.4.
    Old Unix programmers never die, they just mv to /dev/null

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured